﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}
@section header {
    <link href="~/lib/summernote/0.8.15/summernote.min.css" rel="stylesheet" type="text/css">
    <script src='~/lib/summernote/0.8.15/summernote.js' type="text/javascript"></script>
    <script src='~/lib/summernote/0.8.15/lang/summernote-zh-CN.min.js' type="text/javascript"></script>

    <link href="~/lib/imageupload/1.0/css/imgup.min.css" rel="stylesheet" type="text/css">
    <script src='~/lib/imageupload/1.0/js/imgup.min.js' type="text/javascript"></script>

    <link href="~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.css" rel="stylesheet" type="text/css">
    <script src='~/lib/bootstrap.tagsinput/0.8.0/bootstrap-tagsinput.min.js' type="text/javascript"></script>
}

<!DOCTYPE html lang="zh-CN">
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工序生产日报表</title>

    <style>
        /* 保持原有样式不变 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background-color: #f9fafb;
            padding: 16px;
            color: #1f2937;
            font-size: 12px;
        }

        .container {
            width: 95%;
            margin: 0 auto;
        }

        header {
            margin-bottom: 16px;
        }

        h1 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 6px;
        }

        h2 {
            font-size: 16px;
        }

        .text-gray-600 {
            color: #6b7280;
            font-size: 11px;
        }

        .table-container {
            overflow-x: auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            margin-bottom: 16px;
        }

        .virtual-scroll-container {
            max-height: 500px;
            overflow-y: auto;
            position: relative;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
        }

        th, td {
            border: 1px solid #d1d5db;
            padding: 4px 6px;
            text-align: left;
            line-height: 1.3;
            height: 22px;
        }

        #projectTable th, #projectTable td {
            height: 18px;
        }

        th {
            background-color: #dbeafe;
            font-weight: bold;
            font-size: 10px;
            cursor: default;
        }

        tr:hover {
            background-color: transparent;
        }

        .excel-header {
            background-color: #dbeafe;
            font-weight: bold;
        }

        .excel-cell {
            border: 1px solid #d1d5db;
        }

        .text-right {
            text-align: right;
        }

        .font-medium {
            font-weight: 500;
        }

        .risk-badge {
            padding: 1px 4px;
            border-radius: 9999px;
            font-size: 10px;
            display: inline-block;
        }

        .risk-high {
            background: #fee2e2;
            color: #991b1b;
        }

        .risk-medium {
            background: #fef3c7;
            color: #92400e;
        }

        .risk-low {
            background: #dbeafe;
            color: #1e40af;
        }

        .risk-none {
            background: #d1d5db;
            color: #065f46;
        }

        .text-green-600 {
            color: #10b981;
        }

        .text-blue-600 {
            color: #3b82f6;
        }

        .text-yellow-600 {
            color: #f59e0b;
        }

        .text-red-600 {
            color: #ef4444;
        }

        footer {
            text-align: center;
            color: #6b7280;
            font-size: 10px;
            margin-top: 24px;
        }

        .indent-1 {
            padding-left: 12px;
        }

        .filter-container {
            position: relative;
            display: inline-block;
            width: 100%;
        }

        .filter-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            cursor: pointer;
        }

        .filter-icon {
            margin-left: 4px;
            font-size: 10px;
            color: #6b7280;
        }

        .filter-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 4px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 6px;
            z-index: 1000;
            max-height: 250px;
            min-width: 180px;
            overflow-y: auto;
            font-size: 11px;
        }

        .filter-item {
            display: flex;
            align-items: center;
            padding: 3px 6px;
            cursor: pointer;
        }

            .filter-item:hover {
                background-color: #f3f4f6;
            }

            .filter-item input {
                margin-right: 6px;
                transform: scale(0.85);
            }

        .filter-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 6px;
            padding-top: 6px;
            border-top: 1px solid #d1d5db;
        }

            .filter-actions button {
                margin-left: 6px;
                padding: 3px 6px;
                border: 1px solid #d1d5db;
                border-radius: 4px;
                background: white;
                cursor: pointer;
                font-size: 10px;
            }

                .filter-actions button:hover {
                    background-color: #f3f4f6;
                }

        .filter-count {
            margin-left: 6px;
            font-size: 10px;
            color: #6b7280;
        }

        #clearAllFilters {
            padding: 3px 8px;
            font-size: 11px;
        }

        .pagination-info {
            padding: 6px;
            font-size: 11px;
            color: #6b7280;
            text-align: right;
        }

        .no-data {
            text-align: center;
            padding: 20px;
            color: #6b7280;
            font-style: italic;
        }

        .error-message {
            text-align: center;
            padding: 20px;
            color: #ef4444;
            font-weight: bold;
        }

        .loading-message {
            text-align: center;
            padding: 20px;
            color: #6b7280;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>工序生产日报表</h1>
            <p class="text-gray-600">日期：<span id="currentDate"></span></p>
        </header>

        <div class="table-container">
            <table id="productionTable">
                <thead>
                    <tr>
                        <th class="excel-header" colspan="13">生产进度跟踪</th>
                    </tr>
                    <tr>
                        <th class="excel-header" style="width: 9%;" rowspan="3">日期</th>
                        <th class="excel-header" style="width: 40%;" rowspan="3">生产基地</th>
                        <th class="excel-header" style="width: 4%;" rowspan="3">订单数量</th>
                        <th class="excel-header" colspan="2" rowspan="3" style="width: 10%;">工序</th>
                        <th class="excel-header" colspan="6" style="width: 24%;">数量</th>
                        <th class="excel-header" style="width: 10%;" rowspan="3">备注</th>
                        <th class="excel-header" style="width: 7%;" rowspan="3">风险</th>
                    </tr>
                    <tr>
                        <th class="excel-header" colspan="3" style="width: 12%;">当日</th>
                        <th class="excel-header" colspan="3" style="width: 12%;">累计</th>
                    </tr>
                    <tr>
                        <th class="excel-header" style="width: 4%;">计划</th>
                        <th class="excel-header" style="width: 4%;">实际</th>
                        <th class="excel-header" style="width: 4%;">GAP</th>
                        <th class="excel-header" style="width: 4%;">计划</th>
                        <th class="excel-header" style="width: 4%;">实际</th>
                        <th class="excel-header" style="width: 4%;">GAP</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <tr>
                        <td colspan="13" class="loading-message">正在加载数据...</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="flex justify-between items-center mb-3">
            <h2 class="text-xl font-bold">项目分组</h2>
            <button id="clearAllFilters" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded">
                清除所有筛选
            </button>
        </div>

        <div class="table-container mt-6">
            <div class="virtual-scroll-container">
                <table id="projectTable">
                    <thead>
                        <tr>
                            <th class="excel-header" colspan="18">项目跟踪</th>
                        </tr>
                        <tr>
                            <th class="excel-header" style="width: 9%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="CustomerOrderNumber">
                                        <span>客户订单号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 5%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="WorkOrderNumber">
                                        <span>工令号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 8%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="Customer">
                                        <span>客户</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 12%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="ProjectName">
                                        <span>项目名称</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 6%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="CustomerDeliveryDate">
                                        <span>客户交期</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 10%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="ProductNumber">
                                        <span>产品编号</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" style="width: 4%;" rowspan="3">
                                <div class="filter-container">
                                    <div class="filter-header" data-column="OrderQuantity">
                                        <span>订单数量</span>
                                        <span class="filter-icon">▼</span>
                                    </div>
                                </div>
                            </th>
                            <th class="excel-header" colspan="2" rowspan="3" style="width: 10%;">
                                <span>工序</span>
                            </th>
                            <th class="excel-header" colspan="6" style="width: 24%;">数量</th>
                            <th class="excel-header" style="width: 4%;" rowspan="3">生产进度</th>
                            <th class="excel-header" style="width: 24%;" rowspan="3">备注</th>
                        </tr>
                        <tr>
                            <th class="excel-header" colspan="3" style="width: 12%;">当日</th>
                            <th class="excel-header" colspan="3" style="width: 12%;">累计</th>
                        </tr>
                        <tr>
                            <th class="excel-header" style="width: 4%;">计划</th>
                            <th class="excel-header" style="width: 4%;">实际</th>
                            <th class="excel-header" style="width: 4%;">GAP</th>
                            <th class="excel-header" style="width: 4%;">计划</th>
                            <th class="excel-header" style="width: 4%;">实际</th>
                            <th class="excel-header" style="width: 4%;">GAP</th>
                        </tr>
                    </thead>
                    <tbody id="projectTableBody">
                        <tr>
                            <td colspan="18" class="loading-message">正在加载数据...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div id="dataInfo" class="pagination-info"></div>
        </div>

        <footer>
            <p>工序生产日报表 - 生成时间: <span id="generationTime"></span></p>
            <p style="margin-top: 2px;">生产管理系统 © 2025</p>
        </footer>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 设置日期和时间
            const today = new Date();
            const formattedDate = today.toISOString().split('T')[0];
            const [hours, minutes] = [
                today.getHours().toString().padStart(2, '0'),
                today.getMinutes().toString().padStart(2, '0')
            ];
            var projectDataArray = [];

            document.getElementById('currentDate').textContent = formattedDate;
            document.getElementById('generationTime').textContent = `${formattedDate} ${hours}:${minutes}`;

            // 存储筛选条件
            let filterConditions = {};

            // 显示错误信息
            const showError = (message, tableId) => {
                const tableBody = document.getElementById(tableId);
                tableBody.innerHTML = '';
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="${tableId === 'tableBody' ? '13' : '18'}" class="error-message">${message}</td>`;
                tableBody.appendChild(row);

                if (tableId === 'projectTableBody') {
                    document.getElementById('dataInfo').textContent = '数据加载失败';
                }
            };

            // 显示加载状态
            const showLoading = (tableId) => {
                const tableBody = document.getElementById(tableId);
                tableBody.innerHTML = '';
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="${tableId === 'tableBody' ? '13' : '18'}" class="loading-message">正在加载数据...</td>`;
                tableBody.appendChild(row);
            };

            // 获取数据
            const loadData = () => {
                showLoading('tableBody');
                showLoading('projectTableBody');

                ys.ajax({
                    url: '@Url.Content("~/PMCManage/Schedule/GetDayPanel")',
                    type: "post",
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    data: { Date: new Date().toISOString() },
                    success: function (obj) {
                        if (obj && obj.length > 0) {
                            projectDataArray = obj;
                            // 初始渲染
                            applyFiltersAndRender();
                        } else {
                            // 没有数据
                            projectDataArray = [];
                            showError('暂无生产数据', 'tableBody');
                            showError('暂无项目数据', 'projectTableBody');
                            document.getElementById('dataInfo').textContent = '共 0 条数据';
                        }
                    },
                    error: function (_xhr, _status, error) {
                        console.error("API请求失败:", error);
                        // 请求失败
                        projectDataArray = [];
                        showError('数据加载失败，请稍后重试', 'tableBody');
                        showError('数据加载失败，请稍后重试', 'projectTableBody');
                        document.getElementById('dataInfo').textContent = '数据加载失败';
                    }
                });
            };

            // 从项目数据计算汇总数据 - 动态获取工序结构
            const calculateSummaryData = (projects) => {
                if (!projects || projects.length === 0) {
                    return {
                        Date: formattedDate,
                        OrderQuantity: 0,
                        Processes: []
                    };
                }

                // 从第一个项目获取工序结构
                const firstProject = projects[0];
                if (!firstProject.Processes || firstProject.Processes.length === 0) {
                    return {
                        Date: formattedDate,
                        OrderQuantity: 0,
                        Processes: []
                    };
                }

                // 动态构建工序结构
                const summary = {
                    Date: formattedDate,
                    OrderQuantity: 0,
                    Processes: firstProject.Processes.map(level1 => ({
                        Name: level1.Name,
                        Children: level1.Children.map(level2 => ({
                            Name: level2.Name,
                            TodayPlan: 0,
                            TodayActual: 0,
                            TotalPlan: 0,
                            TotalActual: 0,
                            Remark: "系统自动汇总"
                        }))
                    }))
                };

                // 累加所有项目的订单数量
                summary.OrderQuantity = projects.reduce((sum, project) => sum + project.OrderQuantity, 0);

                // 累加各工序数据
                projects.forEach(project => {
                    project.Processes.forEach(level1 => {
                        // 找到对应的一级工序
                        const summaryLevel1 = summary.Processes.find(p => p.Name === level1.Name);
                        if (!summaryLevel1) return;

                        level1.Children.forEach(level2 => {
                            // 找到对应的二级工序
                            const summaryLevel2 = summaryLevel1.Children.find(c => c.Name === level2.Name);
                            if (!summaryLevel2) return;

                            // 累加数据
                            summaryLevel2.TodayPlan += level2.TodayPlan || 0;
                            summaryLevel2.TodayActual += level2.TodayActual || 0;
                            summaryLevel2.TotalPlan += level2.TotalPlan || 0;
                            summaryLevel2.TotalActual += level2.TotalActual || 0;
                        });
                    });
                });

                return summary;
            };

            // 获取所有唯一值用于筛选
            const getUniqueValues = (column) => {
                const values = new Set();
                if (column !== 'process') {
                    projectDataArray.forEach(project => {
                        if (project[column] !== undefined) {
                            values.add(project[column]);
                        }
                    });
                }
                return Array.from(values).sort();
            };

            // 创建筛选下拉框
            const createFilterDropdown = (column, container) => {
                const existingDropdown = container.querySelector('.filter-dropdown');
                if (existingDropdown) existingDropdown.remove();

                const dropdown = document.createElement('div');
                dropdown.className = 'filter-dropdown';
                const uniqueValues = getUniqueValues(column);

                // 添加搜索框
                const searchInput = document.createElement('input');
                searchInput.type = 'text';
                searchInput.placeholder = '搜索...';
                searchInput.className = 'w-full p-2 mb-2 border rounded';
                dropdown.appendChild(searchInput);

                // 全选/取消全选
                const selectAllDiv = document.createElement('div');
                selectAllDiv.className = 'filter-item';
                const columnFilter = filterConditions[column] || [];
                const allSelected = columnFilter.length === 0 || columnFilter.length === uniqueValues.length;
                selectAllDiv.innerHTML = `
                    <input type="checkbox" id="selectAll-${column}" ${allSelected ? 'checked' : ''}>
                    <label for="selectAll-${column}">全选</label>
                `;
                dropdown.appendChild(selectAllDiv);

                // 分隔线
                const divider = document.createElement('div');
                divider.className = 'border-t border-gray-200 my-2';
                dropdown.appendChild(divider);

                // 筛选选项
                const valuesContainer = document.createElement('div');
                uniqueValues.forEach(value => {
                    const itemDiv = document.createElement('div');
                    itemDiv.className = 'filter-item';
                    const isSelected = !filterConditions[column] ||
                                      filterConditions[column].length === 0 ||
                                      filterConditions[column].includes(value);
                    itemDiv.innerHTML = `
                        <input type="checkbox" id="${column}-${value}" value="${value}" ${isSelected ? 'checked' : ''}>
                        <label for="${column}-${value}">${value}</label>
                    `;
                    valuesContainer.appendChild(itemDiv);
                });
                dropdown.appendChild(valuesContainer);

                // 操作按钮
                const actionsDiv = document.createElement('div');
                actionsDiv.className = 'filter-actions';
                actionsDiv.innerHTML = `
                    <button id="clear-${column}">清除筛选</button>
                    <button id="apply-${column}">应用筛选</button>
                `;
                dropdown.appendChild(actionsDiv);
                container.appendChild(dropdown);

                // 全选事件
                document.getElementById(`selectAll-${column}`).addEventListener('change', function(e) {
                    valuesContainer.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                        checkbox.checked = e.target.checked;
                    });
                });

                // 搜索功能
                searchInput.addEventListener('input', function(e) {
                    const searchTerm = e.target.value.toLowerCase();
                    valuesContainer.querySelectorAll('.filter-item').forEach(item => {
                        const label = item.querySelector('label').textContent.toLowerCase();
                        item.style.display = label.includes(searchTerm) ? 'flex' : 'none';
                    });
                });

                // 清除筛选
                document.getElementById(`clear-${column}`).addEventListener('click', function() {
                    if (filterConditions[column]) delete filterConditions[column];
                    dropdown.remove();
                    applyFiltersAndRender();
                });

                // 应用筛选
                document.getElementById(`apply-${column}`).addEventListener('click', function() {
                    const selectedValues = Array.from(valuesContainer.querySelectorAll('input[type="checkbox"]:checked'))
                        .map(checkbox => checkbox.value);
                    if (selectedValues.length === uniqueValues.length) {
                        if (filterConditions[column]) delete filterConditions[column];
                    } else {
                        filterConditions[column] = selectedValues;
                    }
                    dropdown.remove();
                    applyFiltersAndRender();
                });

                return dropdown;
            };

            // 应用筛选并重新渲染
            const applyFiltersAndRender = () => {
                // 如果没有数据，直接返回
                if (!projectDataArray || projectDataArray.length === 0) {
                    return;
                }

                let filteredData = [...projectDataArray];

                // 应用筛选条件
                Object.keys(filterConditions).forEach(column => {
                    const values = filterConditions[column];
                    if (column !== 'process') {
                        filteredData = filteredData.filter(project => {
                            if (column === 'OrderQuantity') {
                                return values.includes(project[column].toString());
                            }
                            return values.includes(project[column]);
                        });
                    }
                });

                // 计算汇总数据并渲染上半部分表格
                const summaryData = calculateSummaryData(filteredData);
                renderTable(summaryData);

                // 渲染下半部分项目表格
                renderProjectTable(filteredData);
                updateFilterIcons();
            };

            // 更新筛选图标状态
            const updateFilterIcons = () => {
                document.querySelectorAll('.filter-header').forEach(header => {
                    const column = header.dataset.column;
                    const icon = header.querySelector('.filter-icon');
                    if (filterConditions[column] && filterConditions[column].length > 0) {
                        icon.textContent = '▲';
                        icon.style.color = '#dc2626';
                    } else {
                        icon.textContent = '▼';
                        icon.style.color = '#6b7280';
                    }
                });
            };

            // 初始化筛选功能
            const initFilters = () => {
                document.querySelectorAll('.filter-header').forEach(header => {
                    header.addEventListener('click', function(e) {
                        e.stopPropagation();
                        const column = this.dataset.column;
                        const container = this.parentElement;

                        document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                            if (!container.contains(dropdown)) dropdown.remove();
                        });

                        const existingDropdown = container.querySelector('.filter-dropdown');
                        if (existingDropdown) {
                            existingDropdown.remove();
                        } else {
                            createFilterDropdown(column, container);
                        }
                    });
                });

                document.addEventListener('click', function(e) {
                    const isClickInsideFilter = e.target.closest('.filter-container');
                    if (!isClickInsideFilter) {
                        document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                            dropdown.remove();
                        });
                    }
                });
            };

            // 清除所有筛选
            document.getElementById('clearAllFilters').addEventListener('click', function() {
                filterConditions = {};
                applyFiltersAndRender();
                document.querySelectorAll('.filter-dropdown').forEach(dropdown => {
                    dropdown.remove();
                });
            });

            // 渲染项目跟踪表格
            const renderProjectTable = (projects) => {
                const tableBody = document.getElementById('projectTableBody');
                tableBody.innerHTML = '';

                if (!projects || projects.length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = `<td colspan="18" class="no-data">暂无项目数据</td>`;
                    tableBody.appendChild(row);
                    document.getElementById('dataInfo').textContent = `共 0 条数据`;
                    return;
                }

                document.getElementById('dataInfo').textContent = `共 ${projects.length} 条数据`;

                projects.forEach((projectData, projectIndex) => {
                    // 计算项目总行数
                    const totalRows = projectData.Processes ?
                        projectData.Processes.reduce((sum, item) => sum + (item.Children ? item.Children.length : 0), 0) : 0;

                    // 如果没有工序数据，显示一行空数据
                    if (totalRows === 0) {
                        const row = document.createElement('tr');
                        row.appendChild(createCell(projectData.CustomerOrderNumber, '', 1));
                        row.appendChild(createCell(projectData.WorkOrderNumber, 'font-medium', 1));
                        row.appendChild(createCell(projectData.Customer, '', 1));
                        row.appendChild(createCell(projectData.ProjectName, '', 1));
                        row.appendChild(createCell(projectData.CustomerDeliveryDate, '', 1));
                        row.appendChild(createCell(projectData.ProductNumber, '', 1));
                        row.appendChild(createCell(projectData.OrderQuantity, '', 1));
                        row.appendChild(createCell('', '', 1)); // 一级工序
                        row.appendChild(createCell('', 'indent-1')); // 二级工序
                        row.appendChild(createCell('', 'text-right')); // 当日计划
                        row.appendChild(createCell('', 'text-right')); // 当日实际
                        row.appendChild(createCell('', 'text-right')); // 当日GAP
                        row.appendChild(createCell('', 'text-right')); // 累计计划
                        row.appendChild(createCell('', 'text-right')); // 累计实际
                        row.appendChild(createCell('', 'text-right')); // 累计GAP
                        row.appendChild(createCell('', 'text-right font-medium')); // 生产进度
                        row.appendChild(createCell('')); // 备注
                        tableBody.appendChild(row);
                        return;
                    }

                    projectData.Processes.forEach((processLevel1, level1Index) => {
                        const level2List = processLevel1.Children || [];

                        level2List.forEach((processLevel2, level2Index) => {
                            const row = document.createElement('tr');

                            // 添加项目分隔线
                            if (projectIndex > 0 && level1Index === 0 && level2Index === 0) {
                                const separatorRow = document.createElement('tr');
                                separatorRow.appendChild(createCell('', 'border-t-2 border-gray-400', 1, 18));
                                tableBody.appendChild(separatorRow);
                            }

                            // 客户订单号（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.CustomerOrderNumber, '', totalRows));
                            }

                            // 工令号（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.WorkOrderNumber, 'font-medium', totalRows));
                            }

                            // 客户（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.Customer, '', totalRows));
                            }

                            // 项目名称（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.ProjectName, '', totalRows));
                            }

                            // 客户交期（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.CustomerDeliveryDate, '', totalRows));
                            }

                            // 产品编号（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.ProductNumber, '', totalRows));
                            }

                            // 订单数量（合并项目所有行）
                            if (level1Index === 0 && level2Index === 0) {
                                row.appendChild(createCell(projectData.OrderQuantity, '', totalRows));
                            }

                            // 一级工序（合并当前工序所有行）
                            if (level2Index === 0) {
                                row.appendChild(createCell(processLevel1.Name, 'font-medium', level2List.length));
                            }

                            // 二级工序
                            row.appendChild(createCell(processLevel2.Name, 'indent-1'));

                            // 当日计划
                            row.appendChild(createCell(processLevel2.TodayPlan, 'text-right'));

                            // 当日实际
                            row.appendChild(createCell(processLevel2.TodayActual, 'text-right'));

                            // 当日GAP
                            const todayGap = processLevel2.TodayActual - processLevel2.TodayPlan;
                            const todayGapCell = createCell(todayGap, 'text-right');
                            if (todayGap < 0) todayGapCell.classList.add('text-red-600');
                            else todayGapCell.classList.add('text-green-600');
                            row.appendChild(todayGapCell);

                            // 累计计划
                            row.appendChild(createCell(processLevel2.TotalPlan, 'text-right'));

                            // 累计实际
                            row.appendChild(createCell(processLevel2.TotalActual, 'text-right'));

                            // 累计GAP
                            const totalGap = processLevel2.TotalActual - processLevel2.TotalPlan;
                            const totalGapCell = createCell(totalGap, 'text-right');
                            if (totalGap < 0) totalGapCell.classList.add('text-red-600');
                            else totalGapCell.classList.add('text-green-600');
                            row.appendChild(totalGapCell);

                            // 生产进度
                            const progressCell = createCell(processLevel2.ProductionProgress, 'text-right font-medium');
                            const progressValue = parseInt(processLevel2.ProductionProgress);
                            if (progressValue >= 100) progressCell.classList.add('text-green-600');
                            else if (progressValue >= 90) progressCell.classList.add('text-blue-600');
                            else if (progressValue >= 70) progressCell.classList.add('text-yellow-600');
                            else progressCell.classList.add('text-red-600');
                            row.appendChild(progressCell);

                            // 备注
                            row.appendChild(createCell(processLevel2.Remark));

                            tableBody.appendChild(row);
                        });
                    });
                });
            };

            // 初始化筛选
            initFilters();

            // 加载数据
            loadData();
        });

        // 创建单元格辅助函数
        function createCell(text, className = '', rowspan = 1, colspan = 1) {
            const cell = document.createElement('td');
            cell.className = `excel-cell ${className}`;
            cell.textContent = text;
            if (rowspan > 1) cell.setAttribute('rowspan', rowspan);
            if (colspan > 1) cell.setAttribute('colspan', colspan);
            return cell;
        }

        // 计算风险等级
        function calculateRisk(progress) {
            if (progress >= 99) return '无';
            else if (progress >= 80) return '低';
            else if (progress >= 70) return '中';
            else return '高';
        }

        // 渲染汇总表格
        function renderTable(data) {
            const tableBody = document.getElementById('tableBody');
            tableBody.innerHTML = '';

            if (!data.Processes || data.Processes.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `<td colspan="13" class="no-data">暂无汇总数据</td>`;
                tableBody.appendChild(row);
                return;
            }

            const totalRows = data.Processes.reduce((sum, item) => sum + (item.Children ? item.Children.length : 0), 0);

            data.Processes.forEach((processLevel1, level1Index) => {
                const level2List = processLevel1.Children || [];

                level2List.forEach((processLevel2, level2Index) => {
                    const row = document.createElement('tr');

                    // 日期（合并所有行）
                    if (level1Index === 0 && level2Index === 0) {
                        row.appendChild(createCell(data.Date, '', totalRows));
                    }

                    // 生产基地（合并所有行）
                    if (level1Index === 0 && level2Index === 0) {
                        row.appendChild(createCell("江西一舟", 'font-medium', totalRows));
                    }

                    // 订单数量（合并所有行）
                    if (level1Index === 0 && level2Index === 0) {
                        row.appendChild(createCell(data.OrderQuantity, '', totalRows));
                    }

                    // 一级工序（合并当前工序所有行）
                    if (level2Index === 0) {
                        row.appendChild(createCell(processLevel1.Name, 'font-medium', level2List.length));
                    }

                    // 二级工序
                    row.appendChild(createCell(processLevel2.Name, 'indent-1'));

                    // 当日计划
                    row.appendChild(createCell(processLevel2.TodayPlan, 'text-right'));

                    // 当日实际
                    row.appendChild(createCell(processLevel2.TodayActual, 'text-right'));

                    // 当日GAP
                    const todayGap = processLevel2.TodayActual - processLevel2.TodayPlan;
                    const todayGapCell = createCell(todayGap, 'text-right');
                    todayGapCell.style.backgroundColor = todayGap >= 0 ? '#d1fae5' : '#fee2e2';
                    row.appendChild(todayGapCell);

                    // 累计计划
                    row.appendChild(createCell(processLevel2.TotalPlan, 'text-right'));

                    // 累计实际
                    row.appendChild(createCell(processLevel2.TotalActual, 'text-right'));

                    // 累计GAP
                    const totalGap = processLevel2.TotalActual - processLevel2.TotalPlan;
                    const totalGapCell = createCell(totalGap, 'text-right');
                    totalGapCell.style.backgroundColor = totalGap >= 0 ? '#d1fae5' : '#fee2e2';
                    row.appendChild(totalGapCell);

                    // 备注
                    row.appendChild(createCell(processLevel2.Remark));

                    // 风险
                    const progress = processLevel2.TotalPlan > 0
                        ? (processLevel2.TotalActual / processLevel2.TotalPlan) * 100
                        : 0;
                    const risk = calculateRisk(progress);
                    const riskCell = createCell('');
                    const riskBadge = document.createElement('span');
                    riskBadge.textContent = risk;
                    switch(risk) {
                        case '无': riskBadge.className = 'risk-badge risk-none'; break;
                        case '低': riskBadge.className = 'risk-badge risk-low'; break;
                        case '中': riskBadge.className = 'risk-badge risk-medium'; break;
                        case '高': riskBadge.className = 'risk-badge risk-high'; break;
                    }
                    riskCell.appendChild(riskBadge);
                    row.appendChild(riskCell);

                    tableBody.appendChild(row);
                });
            });
        }
    </script>
</body>
</html>